-- metscrape - bulk-download weather forecasts.
-- Copyright (C) 2013  Jack Kelly <jack@jackkelly.name>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Scraper (Scraper(..), scrape) where

import qualified Data.ByteString as BS
import Control.Exception
import Control.Monad
import Network.HTTP
import Network.URI (parseURI)
import Prelude hiding (catch)
import System.Directory
import System.FilePath
import System.IO

data Scraper = WGet [(String, FilePath)]
             | IOWGet (IO [(String, FilePath)])
             | Munge String (String -> IO String) FilePath

scrape :: Scraper -> IO ()
scrape (WGet files) = mapM_ scrapeOne files where
    scrapeOne (url, path) = do
      createDirectoryIfMissing True $ dropFileName path
      putStrLn $ url ++ " -> " ++ path
      get url >>= BS.writeFile path
    get url = let uri = case parseURI url of
                          Nothing -> error $ "Invalid URI: " ++ url
                          Just u -> u in
              catch (simpleHTTP (defaultGETRequest_ uri) >>= getResponseBody)
                    (\e -> do
                       let msg = show (e :: IOException)
                       hPutStrLn stderr ("Warning: " ++ msg)
                       get url)
scrape (IOWGet f) = f >>= (scrape . WGet)
scrape (Munge url f path) = do
  createDirectoryIfMissing True $ dropFileName path
  putStrLn $ url ++ " -> " ++ path
  let grabit = (simpleHTTP (getRequest url)
                >>= getResponseBody
                >>= f
                >>= writeFile path)
  let get = catch grabit (\e -> do let msg = show (e :: IOException)
                                   hPutStrLn stderr ("Warning: " ++ msg)
                                   get)
  get
